# -*- coding: iso-8859-1 -*-
""" It tests the integration between mosa and falkon.It receives a list of benefactor nodes, which have also falkon worker nodes """
import sys
import time
import shutil
import tempfile
import subprocess

def set_storage_hint(filename, node_name):
    print subprocess.Popen(["setfattr", "-n", "placement_hint",  "-v", node_name.strip(), filename], stdout=subprocess.PIPE).communicate()[0]

def set_co_usage(filename, group_name):
    print subprocess.Popen(["setfattr", "-n", "co-usage",  "-v", group_name, filename], stdout=subprocess.PIPE).communicate()[0]

def set_replication(filename, rlevel):
    print subprocess.Popen(["setfattr", "-n", "replication", str(rlevel), filename], stdout=subprocess.PIPE).communicate()[0]

def addmosa_prefix(filename):
    return "mosa://" + filename

def run_falkon_job(file_groups, falkon_path, max_submit_thro,execs2ws, num_threads, max_concurrent_tasks):
    tasks = "\n".join([falkon_task(file_group) for file_group in file_groups])
    num_execs = len(tasks)#nun_execs on falkon's idiom means the number of tasks	
    f = tempfile.NamedTemporaryFile(suffix='.job')
    f.writelines(tasks)
    f.flush()
    subprocess.call([falkon_path, job_path, num_execs, max_submit_thro, execs2ws, num_threads, max_concurrent_tasks])
    f.close()

""" """   
def falkon_task(input_files):
    logical_input = " ".join(input_files)
    mosa_names = " ".join([addmosa_prefix(name) for name in input_files])
    return "md5sum " + logical_input + " %%% "+ logical_input + " %%% " + mosa_names + " %%%  %%%  %%%"

""" """
def place_files(file_groups, ben_nodes, base_input_file):
    for group_index in range(len(file_groups)):
        node = ben_nodes[group_index % len(ben_nodes)]
	for file in file_groups[group_index]:
       	    shutil.copy(base_input_file, file)
            annot_facade.set_co_usage(filename, node)

""" Main Flow """
if (len(sys.argv) < 5):
    print "usage: args mount_point base_input_file cousage_size falkon_path"
    sys.exit(2)

mount_point = sys.argv[1]
base_input_file = sys.argv[2]
cousage_size = int(sys.argv[3])

falkon_path = sys.argv[4]

ben_nodes = sys.stdin.readlines()
num_nodes = len(ben_nodes)

#falkon job parameters
max_submit_thro = num_nodes
execs2ws = num_nodes
num_threads = 1
max_concur_tasks = num_nodes

begin_stage = time.clock()
cousage_groups = {}
for node in ben_nodes:
    group = set()
    for i in range(cousage_size):
	node = node.strip()
    	new_filename = mount_point + "/" + node + "." + str(i)
    	file_stage_begin = time.clock() # start time stamp
    	shutil.copyfile(base_input_file, new_filename)
    	set_co_usage(new_filename, node)
    	print "stage in file\t", new_filename + "\t", time.clock() - file_stage_begin	# stop time stamp
	group.add(new_filename)
    cousage_groups[node] = group
    
print "stage in delay\t ", time.clock() - begin_stage

#run_falkon_job(co_usage_group.values(), falkon_path, max_submit_thro, execs2ws, num_threads, max_concur_tasks)